package com.sd365.permission.centre.service.impl;

import com.sd365.permission.centre.pojo.vo.CacheInfoVO;
import com.sd365.permission.centre.pojo.vo.KeyValueVo;
import com.sd365.permission.centre.pojo.vo.OrderChcheVO;
import com.sd365.permission.centre.service.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Version :
 * @PROJECT_NAME: sd365-permission-centre
 * @PACKAGE_NAME:com.sd365.permission.centre.service.impl
 * @NAME: CacheService
 * @author:xuandian
 * @DATE: 2022/7/11 7:50
 * @description:
 */
@Slf4j
@Service
public class CacheServiceImpl implements CacheService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public CacheInfoVO getCacheInfo(String key) {
        CacheInfoVO cacheInfoVO = new CacheInfoVO();
        Set<String> keys = redisTemplate.keys("*");
        if (!CollectionUtils.isEmpty(keys)) {
            List<KeyValueVo> keyVos = new ArrayList<>();
            for (String ignore : keys) {
                KeyValueVo keyVo = new KeyValueVo();
                keyVo.setKey(ignore);
                keyVos.add(keyVo);
            }
            if (StringUtils.isNotEmpty(key)) {
                cacheInfoVO.setKeyVos(keyVos.stream().filter(p -> key.equals(p.getKey())).collect(Collectors.toList()));
            } else {
                cacheInfoVO.setKeyVos(keyVos);
            }
        }
        // 获取redis缓存命令统计信息
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));

        // 获取redis缓存中可用键Key的总数
        Long dbSize = redisTemplate.getRequiredConnectionFactory().getConnection().dbSize();
        log.info("{},{}", dbSize, "dbSize请求到了");
        List<OrderChcheVO> orderChcheVOS = new ArrayList<>();
        if (commandStats != null) {
            commandStats.stringPropertyNames().forEach(keyO -> {
                OrderChcheVO chcheVO = new OrderChcheVO();
                String property = commandStats.getProperty(keyO);
                chcheVO.setName(StringUtils.removeStart(keyO, "cmdstat_"));
                chcheVO.setTotalNum(StringUtils.substringBetween(property, "calls=", ",usec"));
                orderChcheVOS.add(chcheVO);
            });
            List<OrderChcheVO> sortedOrderChcheVOS = orderChcheVOS.stream().sorted(Comparator.comparing(OrderChcheVO::getTotalNum)).collect(Collectors.toList());
            cacheInfoVO.setOrderChcheVOS(sortedOrderChcheVOS);
            cacheInfoVO.setDbSize(dbSize);
        }
        return cacheInfoVO;
    }

    @Override
    public KeyValueVo queryByKey(String key) {
        KeyValueVo keyValueVo = new KeyValueVo();
        if (StringUtils.isNotEmpty(key)) {
            Object value = null;
            //String 类型
            if ("string".equals(Objects.requireNonNull(redisTemplate.type(key)).code())) {
                value = redisTemplate.opsForValue().get(key);
            } else {
                value = redisTemplate.opsForZSet().range(key, 0, -1);
            }
            keyValueVo.setKey(key);
            keyValueVo.setValue(value);
        }
        return keyValueVo;
    }

    @Override
    public Boolean deleteByKey(String key) {
        return redisTemplate.delete(key);
    }

}
